package site.hugboy.reggie.common;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLInput;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] res = ex.getMessage().split(" ");
            String msg = res[2] + "已经存在.";
            return R.error(msg);
        }
        return R.error("未知错误.");
    }

    /**
     * 自定义业务异常处理
     * @return
     */
    @ExceptionHandler(MyException.class)
    public R<String> exHandler(MyException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
